package dentex.youtube.downloader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import dentex.youtube.downloader.FileArrayAdapter;
import dentex.youtube.downloader.Item;
import dentex.youtube.downloader.R;
import dentex.youtube.downloader.queue.FFmpegExtractAudioTask;
import dentex.youtube.downloader.utils.PopUps;
import dentex.youtube.downloader.utils.Utils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Menu;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {


	private String videoId;
	private File currentDir;
	private FileArrayAdapter adapter;
	private File privateAppDir;
	private File privateFile;
	private int cpuVers;
	private boolean isCpuSupported;
	private boolean ffmpegInstalled;
	private File extDir;
	private File extFile;
    private File buffer;

	private  ContextThemeWrapper boxThemeContextWrapper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.share);
		
		
		 currentDir = new File("/sdcard/");
		    fill(currentDir); 
		    
		
		
	}

	
	
	
	private void fill(File f) {
		File[]dirs = f.listFiles(); 
		 this.setTitle("Current Dir: "+f.getName());
		 List<Item>dir = new ArrayList<Item>();
		 List<Item>fls = new ArrayList<Item>();
		 try{
			 for(File ff: dirs)
			 { 
				Date lastModDate = new Date(ff.lastModified()); 
				DateFormat formater = DateFormat.getDateTimeInstance();
				String date_modify = formater.format(lastModDate);
				if(ff.isDirectory()){
					
					
					File[] fbuf = ff.listFiles(); 
					int buf = 0;
					if(fbuf != null){ 
						buf = fbuf.length;
					} 
					else buf = 0; 
					String num_item = String.valueOf(buf);
					if(buf == 0) num_item = num_item + " item";
					else num_item = num_item + " items";
					
					//String formated = lastModDate.toString();
					dir.add(new Item(ff.getName(),num_item,date_modify,ff.getAbsolutePath(),"directory_icon")); 
				}
				else
				{
					   String ext = ff.getAbsolutePath().toString().substring(ff.getAbsolutePath().toString().lastIndexOf(".")+1, ff.getAbsolutePath().toString().length());
					   String    test = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext.toLowerCase()); 
		             //  Toast.makeText(main.this, test, Toast.LENGTH_LONG).show();					    	 

		               
		               if(test==null){
							 
		 					fls.add(new Item(ff.getName(),ff.length() + " Byte", date_modify, ff.getAbsolutePath(),"file_icon"));
	                           }
					        else{ 
					        	
					        if(test.startsWith("text/")){
							 
					        	if(test.contains("htm")){
				 					fls.add(new Item(ff.getName(),ff.length() + " Byte", date_modify, ff.getAbsolutePath(),"html_icon"));

							      }else if(test.contains("css")){
					 					fls.add(new Item(ff.getName(),ff.length() + " Byte", date_modify, ff.getAbsolutePath(),"css_icon"));

							      }else {
					 					fls.add(new Item(ff.getName(),ff.length() + " Byte", date_modify, ff.getAbsolutePath(),"txt_icon"));

							      }
						        
						    }else if(test.startsWith("image/")){
							 
			 					fls.add(new Item(ff.getName(),ff.length() + " Byte", date_modify, ff.getAbsolutePath(),"img_icon"));

						        
						    }else if(test.startsWith("video/")){
							 
			 					fls.add(new Item(ff.getName(),ff.length() + " Byte", date_modify, ff.getAbsolutePath(),"video_icon"));

						   }else if(test.startsWith("application/")) {
							 
							   if(test.contains("zip")||(test.contains("rar"))||(test.contains("tar"))){
				 					fls.add(new Item(ff.getName(),ff.length() + " Byte", date_modify, ff.getAbsolutePath(),"rar_icon"));

							      }
							      else if(test.contains("pdf")){
					 					fls.add(new Item(ff.getName(),ff.length() + " Byte", date_modify, ff.getAbsolutePath(),"pdf_icon"));

							      }
							      else if(test.contains("msword")){
					 					fls.add(new Item(ff.getName(),ff.length() + " Byte", date_modify, ff.getAbsolutePath(),"doc_icon"));

							      }else if(test.contains("powerpoint")){
					 					fls.add(new Item(ff.getName(),ff.length() + " Byte", date_modify, ff.getAbsolutePath(),"ppt_icon"));

							      }else if(test.contains("excel")){
					 					fls.add(new Item(ff.getName(),ff.length() + " Byte", date_modify, ff.getAbsolutePath(),"xls_icon"));

							      }else {
					 					fls.add(new Item(ff.getName(),ff.length() + " Byte", date_modify, ff.getAbsolutePath(),"app_icon"));

							      }
						   }else if(test.startsWith("audio/")) {
							 
			 					fls.add(new Item(ff.getName(),ff.length() + " Byte", date_modify, ff.getAbsolutePath(),"audio_icon"));

						         };  
						       	
					        }
		               
		               
					
					
					
				}
			 }
		 }catch(Exception e)
		 {    
			 
		 }
		 Collections.sort(dir);
		 Collections.sort(fls);
		 dir.addAll(fls);
		 if(!f.getName().equalsIgnoreCase("sdcard"))
			 dir.add(0,new Item("..","Parent Directory","",f.getParent(),"directory_up"));
		 adapter = new FileArrayAdapter(MainActivity.this,R.layout.file_view,dir);
		
			 ListView channelList = (ListView)findViewById(R.id.testshare);
	        channelList.setAdapter(adapter);
	        
	         
	        
	        
	        channelList.setOnItemClickListener(new OnItemClickListener() {

				private View row;

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					Item o = adapter.getItem(arg2);
					if(o.getImage().equalsIgnoreCase("directory_icon")||o.getImage().equalsIgnoreCase("directory_up")){
							currentDir = new File(o.getPath());
							fill(currentDir);
					}
					else
					{     //test si le fichier exist
						
						String type = getMimeType(o.getPath().toString());						
						if(type.contains("video")){
							File videoFileToConvert = new File(o.getPath().toString());
							String brType = "CBR";
							String name = videoFileToConvert.getName().substring(0, videoFileToConvert.getName().lastIndexOf("."));
							File audioFile = new File(videoFileToConvert.getParent()+"/"+name+".wav");
							String brValue = "196";
							char[] ID = null;
							int pos = 0;
							FFmpegExtractAudioTask ff = new FFmpegExtractAudioTask(
									MainActivity.this, 
									videoFileToConvert, audioFile, 
									brType, brValue, 
									null, 
									null, 
									pos);
							ff.execute("");
						}else{
							 Toast.makeText(MainActivity.this, "cannot convert this file ,is not a video file", Toast.LENGTH_LONG).show();
						}
						/*
						 */
//				              Toast.makeText(MainActivity.this, videoFileToConvert.getParent(), Toast.LENGTH_LONG).show();					    	 
//					    
//				              Toast.makeText(MainActivity.this, name, Toast.LENGTH_LONG).show();					    	 
//
//						
					}
				}
	        });
	}
	
	public static String getMimeType(String url)
	 {
	     String type = null;
	     String extension = MimeTypeMap.getFileExtensionFromUrl(url);
	     if (extension != null) {
	         MimeTypeMap mime = MimeTypeMap.getSingleton();
	         type = mime.getMimeTypeFromExtension(extension);
	     }
	     return type;
	 }
	
}
